package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /*
     * 统计给定时间段的营业额
     * */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double turnover = orderMapper.sumByDateTime(beginTime, endTime);
            if(turnover == null){
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }
    /*
     *
     * 统计给定时间段的用户数据（全部和新增）
     * */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin.minusDays(1));
        while(!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        List<Integer> totalUserList = new ArrayList<>();
        //查询截止到指定时间的总用户数量
        for(LocalDate date : dateList){
            LocalDateTime dateTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalUser = userMapper.countByCreateTime(dateTime);
            totalUserList.add(totalUser);
        }
        List<Integer> newUserList = new ArrayList<>();
        //计算出每天新增的用户数量
        for(int i = 1;i < totalUserList.size();++i){
            newUserList.add(totalUserList.get(i) - totalUserList.get(i - 1));
        }
        totalUserList.remove(0);
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /*
     *
     * 统计订单数据
     * */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCountAll = 0;
        Integer validOrderCountAll = 0;
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = orderMapper.countByDateTimeAndStatus(beginTime, endTime, null);
            Integer validOrderCount = orderMapper.countByDateTimeAndStatus(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);

            totalOrderCountAll += orderCount;
            validOrderCountAll += validOrderCount;
        }
        //计算订单完成率
        Double orderCompletionRate = Double.valueOf(validOrderCountAll) / Double.valueOf(totalOrderCountAll);
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCountAll)
                .validOrderCount(validOrderCountAll)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /*
    * 统计销量排名前十
    * */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end){
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<SalesTop10ReportVO> salesTop10ReportVOList = orderDetailMapper.getSalesTop10(beginTime, endTime);
        SalesTop10ReportVO result = new SalesTop10ReportVO();
        result.setNameList(StringUtils.join(salesTop10ReportVOList.stream().map(SalesTop10ReportVO::getNameList).collect(Collectors.toList()), ","));
        result.setNumberList(StringUtils.join(salesTop10ReportVOList.stream().map(SalesTop10ReportVO::getNumberList).collect(Collectors.toList()), ","));
        return result;
    }

    /*
    * 导出运营数据
    * */
    @Override
    public void export(HttpServletResponse response) {
        //获取时间区间
        LocalDateTime beginTime = LocalDateTime.now().minusDays(30).with(LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.now().minusDays(1).with(LocalTime.MAX);

        //查询近30天的概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        XSSFWorkbook xssfWorkbook;
        //获取xssf对象
        try {
            xssfWorkbook = new XSSFWorkbook(resourceAsStream);
            Sheet sheet = xssfWorkbook.getSheetAt(0);
            //设置时间区间
            String date = beginTime + "   至   " + endTime;
            sheet.getRow(1).getCell(1).setCellValue(date);
            //设置营业额
            Row row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            //设置订单完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //设置新增用户
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //设置有效订单数
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            //设置平均客单价
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //设置明细数据
            for(int i = 0;i < 30;++i){
                row = sheet.getRow(7 + i);
                LocalDate currentDate = beginTime.toLocalDate();
                LocalDateTime begin = LocalDateTime.of(currentDate, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(currentDate, LocalTime.MAX);
                //查询当天营业数据
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
                //设置日期
                row.getCell(1).setCellValue(currentDate.toString());
                //设置营业额
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                //设置有效订单数
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                //设置订单完成率
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                //设置平均客单价
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                //设置新增用户
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

                beginTime = beginTime.plusDays(1);
            }

            //通过servlet输出流写出到浏览器
            ServletOutputStream out = response.getOutputStream();
            xssfWorkbook.write(out);
            //释放资源
            out.close();
            xssfWorkbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
